package com.example.demo.captcha;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RequestMapping("/captcha")
@RestController
public class HuToolCaptchaController {
    //注入配置文件对应对象
    @Autowired
    private Captcha captcha;

    //过期时间1分钟 = 60秒 * 1000毫秒
    private static long VALID_TIME_OUT  = 60 * 1000;

    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session){


        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captcha.getWidth(), captcha.getHeight());

        String code = lineCaptcha.getCode();
        //存储session
        session.setAttribute(captcha.getSession().getKey(),code);
        //当前时间
        session.setAttribute(captcha.getSession().getDate(),new Date());

        //验证码写出,可以写到文件,也可以写到流里
        try {
            lineCaptcha.write(response.getOutputStream());
            response.setContentType("image/jpeg");
            response.setCharacterEncoding("utf-8");
            //防止缓存
            response.setHeader("Pragma", "No-cache");

            //输出
            System.out.println("生成的验证码: "+ lineCaptcha.getCode());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @RequestMapping("/check")
    public boolean check(HttpSession session, String captcha1){
        System.out.println("用户输入验证码: "+ captcha1);
        //captcha为空,直接返回false;
        if(!StringUtils.hasLength(captcha1)){
            return false;
        }

        String code = (String) session.getAttribute(captcha.getSession().getKey());
        Date date = (Date) session.getAttribute(captcha.getSession().getDate());
        if(date == null || (System.currentTimeMillis() - date.getTime()) > VALID_TIME_OUT){
            return false;
        }
        //验证码不区分大小写验证验证码是否正确
        return captcha1.equalsIgnoreCase(code);
    }
}
